package chat;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ChatServer{
	private Socket socket;
	private ExecutorService pool;
	private ServerSocket server;
	private ChatRecord<String> chatRecord;
	private List<Socket> socket_list;
	public ChatServer() {
		socket_list=new ArrayList<>();
		chatRecord =new ChatRecord<>();
		chatRecord.addPropChangeListener(new PropertyChangeListener() {			
			@Override
			public void propertyChange(PropertyChangeEvent arg0) {
				for (Socket socket : socket_list) {
					try {
						ObjectOutputStream oos=new ObjectOutputStream(socket.getOutputStream());
						oos.writeObject(arg0.getNewValue());
						oos.flush();
					} catch (Exception e) {
						e.printStackTrace();
					}				
				}
			}
		});
		try {
			pool=Executors.newFixedThreadPool(5);//
			server=new ServerSocket(2828);//需要单独写成一个线程，否则在客户端连接上前会一直处于等待状态
			System.out.println("服务器已启动");
			while(true){
				socket=server.accept();
				chatRecord.add(socket.getInetAddress()+"加入了聊天室");
				socket_list.add(socket);
				pool.execute(new ServerReceive(socket, chatRecord,socket_list));//使用线程池启动线程，效果与下标注相同
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public static void main(String[] args) {
		new ChatServer();
	}
}
